package com.ziki.test.socket.thread;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.text.SimpleDateFormat;

import com.ziki.test.socket.MySocket;
import com.ziki.test.socket.data.DeliverData;
import com.ziki.test.socket.data.SubmitData;
import com.ziki.test.socket.protocol.SMPP;
import com.ziki.test.socket.util.Log;
import com.ziki.test.socket.util.PubFun;

public class DataRecvThread extends Thread {
    private MySocket                mySocket;
    private boolean                 runFlag = true;

    public DataInputStream  dis;

    public DataOutputStream dos;
    private SMPP                        smpp        = new SMPP();
    SimpleDateFormat                sdf         = new SimpleDateFormat("yyyyMMddHHmmss");

    // public DataRecvThread(Socket incoming) {
    // socket = incoming;
    // try {
    // socket.setSoTimeout(30000);
    // dos = new DataOutputStream(new
    // BufferedOutputStream(socket.getOutputStream()));
    // dis = new DataInputStream(new
    // BufferedInputStream(socket.getInputStream()));
    // this.start();
    // }
    // catch (Exception e) {
    // e.printStackTrace();
    // }
    // }

    public DataRecvThread(MySocket mySocket) {
        this.mySocket = mySocket;
        this.runFlag = true;
        this.start();
    }

    public void run() {
        try {
            while (runFlag) {
                byte[] data = mySocket.recvData();
                if (data == null)
                    break;
                parse_smpp(data);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        mySocket.unLink();
    }

    /**
     * 分析接收的SMPP包数据
     * 
     * @param data
     */
    public void parse_smpp(byte[] data) {
        byte[] seqID = new byte[4];
        int commandID = 0;
        int[] commandIDStatus = new int[2];

        try {
            commandID = smpp.parseHead(data, seqID, commandIDStatus);
//          System.out.println(isPrintRecvLog(commandID));
//          System.out.println(isPrintLog(commandID));
            if (commandID == smpp.get_LOGIN_RESP()) { // BIND命令,设置mySocket连接成功
                smpp.parseBodyLoginResp(data, commandIDStatus[1]);
            }
            else if (commandID == smpp.get_LOGIN2_RESP()) { // BIND命令,设置mySocket连接成功
                smpp.parseBodyLoginResp(data, commandIDStatus[1]);
            }
            else if (commandID == smpp.get_EXIT()) { // UNBIND命令,发送UNBIND状态命令,关闭连接
                mySocket.sendData(smpp.getExitResp(seqID));
                mySocket.unLink();
            }
            else if (commandID == smpp.get_EXIT_RESP()) { // UNBIND状态命令,关闭连接
                mySocket.unLink();
            }
            else if (commandID == smpp.get_SUBMIT_RESP()) { // SUBMIT状态命令,去除submitBuffer中的记录,加入到submitRespVector中
                SubmitData submitData = null;// this.findDataFromBuffer(seqID);
                if (submitData != null) {
                    smpp.parseBodySubmitResp(data, submitData);
                    submitData.result = commandIDStatus[1];
                    // MainApp.submitRespVector.add(submitData);
                }
            }
            else if (commandID == smpp.get_DELIVER()) { // DELIVER命令,生成deliverData数据,加入deliverVector,发送接收状态包
                DeliverData deliverData = new DeliverData();
                smpp.parseBodyDeliver(data, deliverData);
                // MainApp.deliverVector.add(deliverData);
                // mySocket.sendData(smpp.getDeliverResp(seqID,
                // deliverData.deliverMsgID));
            }
            /** =========add by song========== */
            else if (commandID == smpp.get_LOGIN2()) {
                byte[] bodyData = PubFun.getByteEnd(data, 16, 16);
                byte[] tmp = smpp.getSendData(smpp.get_LOGIN2_RESP(), 0, seqID, bodyData);
                mySocket.sendData(tmp);
                mySocket.loginFlag = true;
                if(ListenThread.isPrintRecvLog(commandID))
                    Log.printDataLog("服务器接收", data);
                if (ListenThread.isPrintLog(commandID))
                    Log.printDataLog("服务器发送", tmp);
            }
            else if (commandID == smpp.get_LOGIN()) {
                byte[] bodyData = PubFun.getByteEnd(data, 16, 16);
                byte[] tmp = smpp.getSendData(smpp.get_LOGIN_RESP(), 0, seqID, bodyData);
                mySocket.sendData(tmp);
                mySocket.loginFlag = true;
                if(ListenThread.isPrintRecvLog(commandID))
                    Log.printDataLog("服务器接收", data);
                if (ListenThread.isPrintLog(commandID))
                    Log.printDataLog("服务器发送", tmp);
            }
            else if (commandID == smpp.get_LOGIN3()) {
                byte[] bodyData = PubFun.getByteEnd(data, 16, 16);
                byte[] tmp = smpp.getSendData(smpp.get_LOGIN3_RESP(), 0, seqID, bodyData);
                mySocket.sendData(tmp);
                mySocket.loginFlag = true;
                if(ListenThread.isPrintRecvLog(commandID))
                    Log.printDataLog("服务器接收", data);
                if (ListenThread.isPrintLog(commandID))
                    Log.printDataLog("服务器发送", tmp);
            }
            else if (commandID == smpp.get_ACTIVE_TEST()) {
                byte[] tmp = smpp.getHeadResp(16, smpp.get_ACTIVE_TEST_RESP(), seqID);
                mySocket.sendData(tmp);
                if(ListenThread.isPrintRecvLog(commandID))
                    Log.printDataLog("服务器接收", data);
                if (ListenThread.isPrintLog(commandID))
                    Log.printDataLog("服务器发送", tmp);
            }
            else if (commandID == smpp.get_SUBMIT()) {
                MyTimerTask.addCounter();
//              byte[] bodyData = PubFun.toByteArray(PubFun.getSeq(), 9);
                byte[] bodyData = String.valueOf(PubFun.getSeq()).getBytes();
                byte[] tmp = smpp.getSendData(smpp.get_SUBMIT_RESP(), 0, seqID, bodyData);
                mySocket.sendData(tmp);
                if(ListenThread.isPrintRecvLog(commandID))
                    Log.printDataLog("服务器接收", data);
                if (ListenThread.isPrintLog(commandID))
                    Log.printDataLog("服务器发送", tmp);
                byte[] sdata = smpp.parseDeliverStatus(data, new String(bodyData));
                if(sdata != null){
                    mySocket.sendData(sdata);
                    Log.printDataLog("状态报告", sdata);
                }
            }
            else if (commandID == smpp.get_DELIVER_RESP()) {
                if(ListenThread.isPrintRecvLog(commandID))
                    Log.printDataLog("服务器接收", data);
                // sendData(smpp.getHeadResp(16, smpp.get_ACTIVE_TEST_RESP(), seqID));
            }
            /** =========add by song========== */
        }
        catch (Exception ex) {
            Log.write2Log(3, "接收线程", "线程异常，原因：" + ex.getMessage());
            mySocket.loginFlag = false;
        }
    }


    public void stopRun() {
        this.runFlag = false;
        this.interrupt();
    }

    public void threadSleep(int miniSec) {
        try {
            Thread.sleep(miniSec);
        }
        catch (InterruptedException e) {
        }
    }
}
